import React, { useEffect, useState } from "react";
import {
  Button,
  Table,
  message,
  Popconfirm,
  DatePicker,
  Tag,
  Modal,
} from "antd";
import {
  listProducts,
  listUsers,
  listApplications,
  updateApplicationStatus,
  createApplication,
  listRoles,
  listWarehouses,
  listWarehouseProducts,
} from "../../api/ckgl";
import ListApplicationsModal from "./componets/ListApplicationsModal";
import { Application } from "../../api/type/ckgl";

const ListApplications = () => {
  const [returnApplicationList, setReturnApplicationList] = useState<any[]>([]);
  const [totalReturnApplications, setTotalReturnApplications] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(20);
  const [isReturnApplicationModalVisible, setIsReturnApplicationModalVisible] =
    useState(false);
  const [currentReturnApplication, setCurrentReturnApplication] =
    useState<any>(null);
  const [productList, setProductList] = useState<any[]>([]);
  const [list, setList] = useState<any[]>([]);
  const [warehouses, setWarehouses] = useState<any[]>([]);
  const [warehouseProductList, setWarehouseProductList] = useState<any[]>([]);

  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
      width: 80,
    },
    {
      title: "物品名称",
      dataIndex: "product_name",
      key: "product_name",
      width: 100,
      render: (text: string) => <span>{text}</span>,
    },
    {
      title: "申请人名称",
      dataIndex: "applicant_name",
      key: "applicant_name",
      width: 130,
      render: (text: string) => <span>{text}</span>,
    },
    {
      title: "物资管理员名称",
      dataIndex: "administrator_name",
      key: "administrator_name",
      width: 130,
      render: (text: string) => <span>{text}</span>,
    },
    {
      title: "申请类型",
      dataIndex: "application_type",
      key: "application_type",
      width: 130,
      render: (application_type: number) => {
        return ["", "借出", "归还"][application_type];
      },
    },
    {
      title: "申请时间",
      dataIndex: "application_date",
      key: "application_date",
      width: 130,
      render: (text: string) => <span>{text}</span>,
    },
    {
      title: "预计归还日期，",
      dataIndex: "expected_return_date",
      key: "expected_return_date",
      width: 130,
      render: (text: string) => <span>{text}</span>,
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      width: 130,
      render: (status: number) => {
        return ["", "待处理", "已处理 "][status];
      },
    },
    {
      title: "备注",
      dataIndex: "remarks",
      key: "remarks",
      width: 130,
      render: (text: string) => <span>{text}</span>,
    },
    {
      title: "预计归还日期",
      dataIndex: "expected_return_date",
      key: "expected_return_date",
      width: 130,
      render: (text: string) => <span>{text}</span>,
    },
    {
      title: "操作",
      dataIndex: "id",
      fixed: "right",
      key: "id",
      render: (_: any, record: any) => (
        <>
          {!["picker", "visitor"].includes(localStorage?.role_code) && (
            <Button
              type="link"
              disabled={record.status === 2}
              onClick={() => {
                Modal.confirm({
                  title: "确认？",
                  content: "你确认改成已处理嘛",
                  okText: "确定",
                  cancelText: "取消",
                  onOk() {
                    // 在这里编写确认后的逻辑，例如发送删除请求
                    let msg = "更新成功";
                    updateApplicationStatus({
                      status: 2,
                      application_id: record.id,
                    } as any)
                      .then((res: any) => {
                        if (res?.code !== 0) {
                          message.error(res.msg);
                          return;
                        }
                        message.success(msg);
                      })
                      .finally(() => {
                        reset(currentPage);
                      });
                  },
                  onCancel() {
                    // 在这里编写取消操作的逻辑（如果需要的话）
                    console.log("用户取消了删除操作");
                  },
                });
              }}
            >
              审批
            </Button>
          )}
        </>
      ),
    },
  ];

  const getListReturnApplications = (page: number) => {
    let applicant_id, administrator_id;
    if (["admin", "m-admin"].includes(localStorage?.role_code)) {
      administrator_id = localStorage?.user_id;
    } else {
      applicant_id = localStorage?.user_id;
    }
    if (localStorage?.role_code === "admin") {
      administrator_id = undefined;
      applicant_id = undefined;
    }
    listApplications({
      page: page,
      size: pageSize,
      administrator_id,
      applicant_id,
      //     int32 applicant_id = 3; // 领物人员（user_id）登陆，传applicant_id
      // int32 administrator_id = 4; // 物资管理员或超管登陆（user_id）, 传administrator_id
    }).then((res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      const { applications, total } = res.data;
      setReturnApplicationList(applications);
      setTotalReturnApplications(total);
    });
    // .catch(() => {
    //   let arr = [
    //     {
    //       id: 2,
    //       product_id: 102,
    //       user_id: 1002,
    //       application_type: 2,
    //       application_date: "2023-07-05",
    //       expected_return_date: "",
    //       status: 1,
    //       remarks: "",
    //       product_name: "手机",
    //       user_name: "李四",
    //     },
    //     {
    //       id: 3,
    //       product_id: 102,
    //       user_id: 1002,
    //       application_type: 2,
    //       application_date: "2023-07-05",
    //       expected_return_date: "",
    //       status: 1,
    //       remarks: "",
    //       product_name: "手机",
    //       user_name: "李四",
    //     },
    //   ];
    //   setReturnApplicationList(arr);
    //   setTotalReturnApplications(arr.length);
    // });
  };

  const reset = (page: number) => {
    getListReturnApplications(page);
  };

  const handleReturnApplicationModalOk = async (values: any) => {
    console.log("values", values);
    if (currentReturnApplication) {
      // 更新
    } else {
      // 添加
      let msg = "添加成功";
      console.log("values", values);
      const timeFormat = "YYYY-MM-DD HH:mm:ss";
      const time = "YYYY-MM-DD";

      // const currentTime = moment(new Date()).format(timeFormat);
      // 预计归还日期， 日期格式 2024-03-04 00:00:00，
      const { expected_return_date } = values;
      let _expected_return_date = expected_return_date.format(timeFormat);
      // let _expected_return_date = `${expected_return_date.format(
      //   time
      // )} 00:00:00`;
      console.log("_expected_return_date", _expected_return_date);
      await createApplication({
        applicant_id: localStorage?.user_id || "",
        ...values,
        expected_return_date: _expected_return_date,
      }).then((res: any) => {
        if (res?.code !== 0) {
          message.error(res.msg);
          return;
        }
        message.success(msg);
      });
    }
    // 更新当前页
    reset(currentPage);
    setIsReturnApplicationModalVisible(false);
  };

  useEffect(() => {
    getListReturnApplications(currentPage);
  }, [currentPage]);

  useEffect(() => {
    // getListProducts();
    getListUsers();
    // getListWarehouses();
    getListWarehouseProducts();
  }, []);

  const getListWarehouseProducts = () => {
    // 调用 listWarehouseProducts API，并处理响应
    listWarehouseProducts({
      page: 1,
      size: 300,
    }).then((res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      const { warehouse_products, total } = res.data;
      setWarehouseProductList(warehouse_products);
    });
  };

  // const getListWarehouses = () => {
  //   // 调用 listSuppliers API，并处理响应
  //   listWarehouses({
  //     page: 1,
  //     size: 300,
  //   }).then((res: any) => {
  //     if (res?.code !== 0) {
  //       message.error(res.msg);
  //       return;
  //     }
  //     setWarehouses(res.data?.warehouses || []);
  //   });
  // };

  // const getListProducts = () => {
  //   // 调用 listProducts API，并处理响应
  //   listProducts({
  //     page: 1,
  //     size: 200,
  //   }).then((res: any) => {
  //     if (res?.code !== 0) {
  //       message.error(res.msg);
  //       return;
  //     }
  //     const { products, total } = res.data;
  //     setProductList(products);
  //   });
  // };

  const getListUsers = () => {
    // 获取 roles
    listRoles({
      page: 1,
      size: 100,
    }).then(async (res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      const { roles } = res.data;
      console.log("roles", roles);
      let currentRole = roles.find((ele: any) => ele.code === "m-admin");
      let roleId = currentRole.id;
      listUsers({
        page: 1,
        size: 300,
        role_id: roleId,
      }).then((res: any) => {
        console.log(res);
        if (res?.code !== 0) {
          message.error(res.msg);
          return;
        }
        // admin(系统管理员)，purchaser（采购人员），m-admin（物资管理员），picker（领物），visitor（游客）
        const { users, total } = res.data;

        setList(users);
      });
    });
  };

  return (
    <div>
      {!["m-admin"].includes(localStorage.role_code) && (
        <Button
          style={{ marginTop: "7px", marginLeft: "10px", float: "right" }}
          onClick={() => {
            setIsReturnApplicationModalVisible(true);
            setCurrentReturnApplication(null);
          }}
          size="large"
          type="primary"
        >
          创建归还申请
        </Button>
      )}

      <Table
        dataSource={returnApplicationList}
        columns={columns as any}
        scroll={{ x: "max-content" }}
        rowKey="application_id"
        pagination={{
          pageSize,
          defaultCurrent: 1,
          onChange: setCurrentPage,
          total: totalReturnApplications,
        }}
      />
      <ListApplicationsModal
        users={list}
        warehouseProductList={warehouseProductList}
        title={currentReturnApplication ? "更改申请状态" : "创建申请"}
        visible={isReturnApplicationModalVisible}
        onCancel={() => setIsReturnApplicationModalVisible(false)}
        onOk={handleReturnApplicationModalOk}
        defaultValue={currentReturnApplication || {}}
      />
    </div>
  );
};

export default ListApplications;
